<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>回到顶部特效</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            height: 2000px; /* 设置一个较大的高度以便于滚动 */
        }
        .back-to-top {
            position: fixed;
            bottom: 20px;
            right: 30px;
            background-color: #007BFF;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            display: none; /* 默认隐藏 */
        }
        .back-to-top:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>

<h1>欢迎来到回到顶部特效示例</h1>
<p>滚动页面以查看回到顶部按钮。</p>

<button class="back-to-top" id="backToTopBtn">回到顶部</button>

<script>
    // 获取回到顶部按钮
    var backToTopBtn = document.getElementById("backToTopBtn");

    // 当页面滚动超过300像素时显示按钮
    window.onscroll = function() {
        scrollFunction();
    };

    function scrollFunction() {
        if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
            backToTopBtn.style.display = "block";
        } else {
            backToTopBtn.style.display = "none";
        }
    }

    // 点击按钮时返回顶部
    backToTopBtn.onclick = function() {
        document.body.scrollTop = 0; // For Safari
        document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    };
</script>

</body>
</html>